package cn.edu.scau.cmi.yejiancong.ORM_hibernate.DAO;

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

import javax.persistence.criteria.From;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.jupiter.api.Test;

import cn.edu.scau.cmi.yejiancong.ORM_hibernate.Utils.hibernateUtils;
import cn.edu.scau.cmi.yejiancong.ORM_hibernate.entiry.Student;
import cn.edu.scau.cmi.yejiancong.ORM_hibernate.entiry.Teacher;

public class studentDAO {

	private static Session session=hibernateUtils.getSessionFactory().openSession();
	//crud
	@Test
	public static List<Student> getall(){
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			String hql="from Student";
			Query<Student> query=session.createQuery(hql);
			List<Student> list=query.list();
			
			tx.commit();
			return list;
		} catch (Exception e) {
			tx.rollback();// TODO: handle exception
			return null;
		}
	}
	
	
	
	@Test
	public static void add(Student student) {
		
		Transaction tx=null;
		try {
			tx=session.beginTransaction();
			session.save(student);
			tx.commit();
			System.out.println("success");
		} catch (Exception e) {
			System.out.println("error");
			tx.rollback();
			// TODO: handle exception
		}
		
	}
	
	@Test
	public static List<Object[]> getTeach(Integer id) {
		
		Transaction tx=null;
		
		try {
			tx=session.beginTransaction();
			String hql=" from Student s inner join s.teachers where s.id="+id;
			Query<Object[]> query=session.createQuery(hql);
			List<Object[]> list=query.list();
			
			tx.commit();
			return list;
		} catch (Exception e) {
			tx.rollback();
			return null;// TODO: handle exception
		}
	}
	
	@Test
	public static Student get(Integer id) {
		Transaction tx=null;
		
		try {
			System.out.println(id);
			tx=session.beginTransaction();
			Student student =session.get(Student.class, id);
			System.out.println(student.getStudentid());
			tx.commit();
			return student;
		} catch (Exception e) {
			tx.rollback();
			return null;// TODO: handle exception
		}
	}
	
	@Test
	public static void del(Integer id) {
		Transaction tx=null;
		
		try {
			tx=session.beginTransaction();
			session.delete(session.get(Teacher.class, id));
			tx.commit();
			System.out.println("succeed");
		} catch (Exception e) {
			tx.rollback();// TODO: handle exception
		}
	}
	
}
